import axios from 'axios';
import qs from 'qs';
import router from '../../router/index'
import {Notice, LoadingBar} from 'iview';
import {getToken,removeToken,refreshSession} from "../auth";
import config from "../../../config"

axios.defaults.timeout = 60000;
// axios.defaults.baseURL = 'http://localhost:8080';
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? config.build.requestUrl : config.dev.requestUrl;
axios.defaults.withCredentials = true;

//http request 拦截器
axios.interceptors.request.use(
  config => {
    LoadingBar.start();
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'X-Requested-With': 'XMLHttpRequest'
    };
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


axios.interceptors.response.use(
  response =>{
    //用户登录登陆异常
    if (response.data && response.data.code === 405) {
        removeToken();
        router.push("/login");
        LoadingBar.error();
        return Promise.reject('error');
    }

    //服务器异常
    if (response.data && response.data.code === 500) {
      Notice.error({
        title: "服务器返回异常！",
        desc: response.data.msg ? response.data.msg : "服务器返回空的异常信息！"
      });
      LoadingBar.error();
      return Promise.reject('error');
    }

    //服务器提示信息！
    if (response.data && (response.data.code !== 200 && response.data.code !== 201)) {
      Notice.info({
        title: "提示信息！",
        desc: response.data.msg ? response.data.msg : "服务器返回空的提示信息！"
      });
      LoadingBar.error();
      return Promise.reject('error');
    }

    LoadingBar.finish();
    return response;
  },
  err =>{
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '错误请求';
          break;
        case 401:
          err.message = '未授权，请重新登录';
          break;
        case 403:
          err.message = '拒绝访问';
          break;
        case 404:
          err.message = '请求错误,未找到该资源';
          break;
        case 405:
          err.message = '请求方法未允许';
          break;
        case 408:
          err.message = '请求超时';
          break;
        case 500:
          err.message = '服务器端出错';
          break;
        case 501:
          err.message = '网络未实现';
          break;
        case 502:
          err.message = '网络错误';
          break;
        case 503:
          err.message = '服务不可用';
          break;
        case 504:
          err.message = '网络超时';
          break;
        case 505:
          err.message = 'http版本不支持该请求';
          break;
        default:
          err.message = `连接错误${err.response.status}`
      }
      //如果登录信息异常
      debugger;
      if (err.response.data && err.response.data.code === 405) {

        removeToken();
        router.push("/login");
      }
    } else {
      if(err.code === 'ECONNABORTED'){
        err.message = "请求超时！"
      }else{
        err.message = "连接到服务器失败"
      }
    }
    Notice.error({
      title: "请求异常信息！",
      desc: err.message
    });
    LoadingBar.error();
    return Promise.reject(err.response)
  }
);

export default axios;


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, param) {
  refreshSession();
  if(param){
    param.random=Math.random();
  }else{
    param ={random:Math.random()}
  }
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: param
    }).then(response => {
      resolve(response.data);
    }, err => {
      reject(err)
    }).catch()
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data) {
  refreshSession();
  if(data) {
    data.random = Math.random();
  } else {
    data = {random: Math.random()}
  }
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(data))
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      }).catch()
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data) {
  refreshSession();
  return new Promise((resolve, reject) => {
    axios.put(url, qs.stringify(data))
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      }).catch()
  })
}


/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function del(url, data) {
  refreshSession();
  return new Promise((resolve, reject) => {
    axios.delete(url, {
      params: data
    })
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      }).catch()
  })
}
